import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_massage/common_lib/routers/route.dart';
import 'package:flutter_massage/values/colors.dart';
import 'package:flutter_picker/Picker.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';

import '../index.dart';

/// 底部弹出对话框
class ActionBottomSheet {
  // 头部
  static Widget _buildHeader({
    /// 标题
    String? title,

    /// 取消事件
    Function()? onCancel,

    /// 确认事件
    Function()? onConfirm,
  }) {
    return Padding(
      padding: EdgeInsets.fromLTRB(38.w, 25.w, 38.w, 0),
      child: Row(
        children: [
          // 取消 按钮
          ButtonWidget.text(
            '取消',
            onTap: onCancel,
            fontSize: 18,
            textColor: AppColors.textLevelOne,
            hasInkWell: false,
          ),

          // title
          Expanded(
            child: TextWidget.oneLine(
              text: title ?? '',
              fontSize: 18,
              color: AppColors.textLevelOne,
              textAlign: TextAlign.center,
            ),
          ),

          // done 按钮
          ButtonWidget.text(
            '确定',
            onTap: onConfirm,
            fontSize: 18,
            textColor: AppColors.primaryGreen,
            hasInkWell: false,
          ),
        ],
      ),
    );
  }

  /// 数据对话框
  static void data({
    /// 上下文 context
    required BuildContext context,

    /// 确认事件
    required Function(List value) onConfirm,

    /// 选取器数据适配器
    required PickerAdapter adapter,

    /// 标题
    String? title,

    /// 默认选中 [index]
    List<int>? selected,
  }) {
    // 准备 picker
    var picker = ActionPicker.array(
      adapter: adapter,
      selected: selected,
    );

    // 调用 标准模式框
    normal(
      context: context,
      contentPadding: const EdgeInsets.all(0),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // 头部栏
          _buildHeader(
            title: title,
            onCancel: () => picker.doCancel(context),
            onConfirm: () {
              picker.doConfirm(context);
              onConfirm(picker.adapter.getSelectedValues());
            },
          ),
          // picker 内容
          picker.makePicker(),
        ],
      ),
    );
  }

  static void actionSheet({
    /// items
    required List<ActionSheetConfig> items,
  }) {
    List<Widget> children = items.map((e) {
      return Column(
        children: [
          ButtonWidget.text(
            e.text,
            alignment: Alignment.center,
            height: 50.w,
            fontSize: 15,
            textColor: AppColors.textLevelOne,
            onTap: () {
              CommonRoute.close();
              e.onTap.call();
            },
            hasInkWell: false,
          ),
          CommonDivider(height: e == items.last ? 10.w : 0.5.w, color: AppColors.grayEe),
        ],
      );
    }).toList();

    Widget cancel = Container(
      padding: EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight * 0.5),
      child: ButtonWidget.text(
        '取消',
        alignment: Alignment.center,
        height: 50.w,
        fontSize: 15,
        textColor: AppColors.textLevelOne,
        onTap: () => CommonRoute.close(),
        hasInkWell: false,
      ),
    );

    // 调用 标准模式框
    normal(
      context: Get.context!,
      contentPadding: const EdgeInsets.all(0),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [...children, cancel],
      ),
    );
  }

  /// 日期选择
  static void showDatePicker({
    String? title,
    required Function(DateTime? dateTime, String year, String month, String day, String hour, String minute) onConfirm,
  }) {
    // 准备 picker
    var picker = ActionPicker.array(
      adapter: DateTimePickerAdapter(
        type: 8,
        months: List.generate(12, (index) => '${index + 1}月'),
        yearSuffix: '年',
        daySuffix: '日',
        yearEnd: DateTime.now().year,
      ),
    );

    // 调用 标准模式框
    normal(
      context: Get.context!,
      contentPadding: const EdgeInsets.all(0),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // 头部栏
          _buildHeader(
            title: title,
            onCancel: () => picker.doCancel(Get.context!),
            onConfirm: () {
              picker.doConfirm(Get.context!);
              DateTime? value = (picker.adapter as DateTimePickerAdapter).value;
              String year = '';
              String month = '';
              String day = '';
              String hour = '';
              String minute = '';
              if (value != null) {
                year = value.year.toString();
                month = value.month.toString();
                day = value.day.toString();
                hour = value.hour.toString();
                minute = value.minute.toString();
              }
              onConfirm(value, year, month, day, hour, minute);
            },
          ),
          // picker 内容
          picker.makePicker(),
        ],
      ),
    );
  }

  /// 身高选择
  static void showHeightPicker({
    String? title,
    int min = 150,
    int max = 200,
    int defaultValue = 165,
    required ValueChanged<String> onConfirm,
  }) {
    List<String> data = [];

    for (int i = min; i <= max; i++) {
      data.add('${i}cm');
    }

    int v = defaultValue - min;
    if (v < 0) v = 0;

    ActionBottomSheet.data(
      title: title ?? '',
      context: Get.context!,
      // 数据
      adapter: PickerDataAdapter(pickerData: data),
      // 默认选中
      selected: [v],
      // 确认回调
      onConfirm: (value) {
        String result = value.isNotEmpty ? value.first : '';
        onConfirm(result);
      },
    );
  }

  /// 体重选择
  static void showWeightPicker({
    String? title,
    int min = 40,
    int max = 100,
    int defaultValue = 50,
    required ValueChanged<String> onConfirm,
  }) {
    List<String> data = [];

    for (int i = min; i <= max; i++) {
      data.add('${i}kg');
    }

    int v = defaultValue - min;
    if (v < 0) v = 0;

    ActionBottomSheet.data(
      title: title ?? '',
      context: Get.context!,
      // 数据
      adapter: PickerDataAdapter(pickerData: data),
      // 默认选中
      selected: [v],
      // 确认回调
      onConfirm: (value) {
        String result = value.isNotEmpty ? value.first : '';
        onConfirm(result);
      },
    );
  }

  /// 学历选择
  static void showEducationPicker({
    String? title,
    String defaultValue = '本科',
    required ValueChanged<String> onConfirm,
  }) {
    List<String> data = ['小学', '初中', '高中', '大专', '本科', '研究生', '博士'];

    int v = data.indexOf(defaultValue);

    ActionBottomSheet.data(
      title: title ?? '',
      context: Get.context!,
      // 数据
      adapter: PickerDataAdapter(pickerData: data),
      // 默认选中
      selected: [v >= 0 ? v : 4],
      // 确认回调
      onConfirm: (value) {
        String result = value.isNotEmpty ? value.first : '';
        onConfirm(result);
      },
    );
  }

  /// 感情状态选择
  static void showMaritalPicker({
    String? title,
    String defaultValue = '单身',
    required ValueChanged<String> onConfirm,
  }) {
    List<String> data = ['单身', '热恋', '已婚', '离异'];

    int v = data.indexOf(defaultValue);

    ActionBottomSheet.data(
      title: title ?? '',
      context: Get.context!,
      // 数据
      adapter: PickerDataAdapter(pickerData: data),
      // 默认选中
      selected: [max(0, v)],
      // 确认回调
      onConfirm: (value) {
        String result = value.isNotEmpty ? value.first : '';
        onConfirm(result);
      },
    );
  }

  // 标准 - 底部弹出 - 模式对话框
  static Future<void> normal({
    required BuildContext context,
    Widget? child,
    EdgeInsetsGeometry? contentPadding,
    bool enableDrag = false,
  }) async {
    /// 弹出底部模式对话框
    return await showMaterialModalBottomSheet(
      // 上下文 context
      context: context,
      // 背景透明
      backgroundColor: Colors.transparent,
      // 启用拖拽
      enableDrag: enableDrag,

      /// 动画时长
      duration: const Duration(milliseconds: 300),
      // 内容
      builder: (context) => AnimatedPadding(
        padding: MediaQuery.of(context).viewInsets,
        duration: const Duration(milliseconds: 150),
        child: Container(
          padding: contentPadding ?? const EdgeInsets.all(10),
          clipBehavior: Clip.antiAlias,
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(20)),
          ),
          // 弹出视图内容区
          child: child,
        ),
      ),
    );
  }

  // Bar 对话框
  static Future<void> barModel(
    Widget child, {
    BuildContext? context,
    double? padding,
    bool enableDrag = true,
  }) async {
    /// 弹出底部模式对话框
    return await showBarModalBottomSheet(
      // 上下文 context
      context: context ?? Get.context!,
      // 背景透明
      backgroundColor: Colors.transparent,
      // 启用拖拽
      enableDrag: enableDrag,
      // expand
      expand: false,
      // 内容
      builder: (context) => SafeArea(
        child: child,
      ),
    );
  }

  // 底部弹出 popModal
  static Future<void> popModal({
    BuildContext? context,
    required Widget child,
    EdgeInsets? safeAreaMinimum,
    bool safeBottom = true,
  }) async {
    return await showMaterialModalBottomSheet(
      context: context ?? Get.context!,
      backgroundColor: Colors.transparent,
      builder: (context) => SafeArea(
        minimum: safeAreaMinimum ?? EdgeInsets.zero,
        bottom: safeBottom,
        child: child,
      ),
    );
  }
}

class ActionSheetConfig {
  final String text;
  final VoidCallback onTap;
  ActionSheetConfig({required this.text, required this.onTap});
}
